package com.masterclient.app.businessmodule.usermodule;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.utils.OkHttpUtils;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.managerlibrary.weixin.WeiXinManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.enums.WXSendTypeEnum;
import com.eoner.middlelib.eventbus.enums.WXSendTypeManager;
import com.eoner.middlelib.eventbus.event.LoginSuccessEvent;
import com.eoner.middlelib.eventbus.event.WXSendCancelEvent;
import com.eoner.middlelib.eventbus.event.WXSendFailedEvent;
import com.eoner.middlelib.eventbus.event.WXSendSuccessEvent;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.MainActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.usermodule.login.BindPhoneActivity;
import com.masterclient.app.businessmodule.usermodule.login.beans.AuthBindData;
import com.masterclient.app.businessmodule.usermodule.login.beans.InviteInfoData;
import com.masterclient.app.businessmodule.usermodule.login.beans.LoginSuccessData;
import com.masterclient.app.businessmodule.usermodule.login.contract.QuickLoginContract;
import com.masterclient.app.businessmodule.usermodule.login.contract.QuickLoginPresenter;
import com.masterclient.app.businessmodule.usermodule.login.invite.BindInviteActivity;
import com.masterclient.app.businessmodule.usermodule.login.util.LoginUtil;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.utils.CaptchaUtil;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：sean
 * 创建时间：2018/3/8 15:33
 * 功能说明：
 */
@Route(path = FCRouterPath.USER_LOGIN_PATH)
public class LoginActivity extends FCBusinessActivity<QuickLoginPresenter> implements QuickLoginContract.View {


    @BindView(R.id.tv_verify)
    TextView tvVerify;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.iv_check)
    ImageView ivCheck;
    @BindView(R.id.view_agreement)
    View viewAgreement;

    SPUtils spUtils;
    String auth_type = "weixin", union_id = "";
    private String phone;
    private String phoneNum;

    CountDownTimer timer1, timer2;
    private boolean isSelected = false;
    private String rewardId = "";

    long time_left = 0;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (nopeAnimator != null && nopeAnimator.isRunning()) {
                nopeAnimator.end();
            }
        }
    };

    @Override
    protected int requireGetLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setVisibility(View.GONE);
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        etPhone.requestFocus();
        spUtils = SPUtils.getInstance();
        showSoftInput(etPhone);

        tvVerify.setClickable(false);
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                try {
                    if (charSequence == null || charSequence.length() == 0) {
                        etPhone.setTypeface(Typeface.DEFAULT);
                        tvVerify.setClickable(false);
                        tvVerify.setBackgroundResource(R.drawable.login_unable_click_bkg);
                        return;
                    }
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < charSequence.length(); i++) {
                        if (i != 3 && i != 8 && charSequence.charAt(i) == ' ') {
                            continue;
                        } else {
                            sb.append(charSequence.charAt(i));
                            if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                                sb.insert(sb.length() - 1, ' ');
                            }
                        }
                    }
                    if (!sb.toString().equals(charSequence.toString())) {
                        int index = start + 1;
                        if (sb.charAt(start) == ' ') {
                            if (before == 0) {
                                index++;
                            } else {
                                index--;
                            }
                        } else {
                            if (before == 1) {
                                index--;
                            }
                        }
                        etPhone.setText(sb.toString());
                        etPhone.setSelection(index);
                    }

                    if (etPhone.getText().toString().length() > 0) {
                        Utils.setDin(etPhone, mContext);
                    } else {
                        etPhone.setTypeface(Typeface.DEFAULT);
                    }
                    if (etPhone.getText().toString().replace(" ", "").length() == 11 && time_left == 0) {
                        tvVerify.setClickable(true);
                        tvVerify.setBackgroundResource(R.drawable.login_able_click_bkg);
                    } else {
                        tvVerify.setClickable(false);
                        tvVerify.setBackgroundResource(R.drawable.login_unable_click_bkg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    ObjectAnimator nopeAnimator;

    private void startLeftAndRightShake() {
        //左右移动
        nopeAnimator = LoginUtil.nope(viewAgreement);
        nopeAnimator.setRepeatCount(ValueAnimator.INFINITE);
        nopeAnimator.start();
    }

    /**
     * 登录成功刷新
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(LoginSuccessEvent event) {
        if (getActivity() != null) {
            getActivity().finish();
        }
    }

    @Override
    public void onDestroy() {
        if (timer1 != null) {
            timer1.cancel();
        }
        if ((timer2 != null)) {
            timer2.cancel();
        }
        super.onDestroy();
    }

    @OnClick({R.id.tv_verify, R.id.tv_agreement, R.id.rl_back, R.id.iv_check_btn})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_agreement:
                startActivitryWithBundle(BridgeActivity.class, new String[][]{{"url", SystemConfigStorage.getInstance().getServiceRuleUrl()}, {"title", "中华大师汇服务协议"}});
                break;
            case R.id.tv_verify:
                //可直接调用验证函数Validate()，本demo采取在异步任务中调用（见UserLoginTask类中）
                //mCaptcha.Validate();
                if (!isSelected) {
                    startLeftAndRightShake();
                    mHandler.sendEmptyMessageDelayed(0, 500);
                    ToastUtil.showToast("请先同意《用户服务协议》");
                    return;
                }
                phoneNum = etPhone.getText().toString().trim().replace(" ", "");
                if (StringsUtils.isPhoneNum(phoneNum)) {
                    if (SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                        if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES) {
                            mPresenter.getCaptcha(phoneNum, "slogin", "");
                        } else {

                        }
                    } else {
                        mPresenter.getCaptcha(phoneNum, "slogin", "");
                        tvVerify.setClickable(false);
                    }
                } else {
                    showToast("请输入正确的手机号");
                }
                break;
            case R.id.iv_check_btn:
                if (isSelected) {
                    isSelected = false;
                    ivCheck.setImageResource(R.mipmap.icon_lg_no_sel);
                } else {
                    ivCheck.setImageResource(R.mipmap.icon_lg_sel);
                    isSelected = true;

                }
                break;
            case R.id.rl_back:
                Objects.requireNonNull(getActivity()).finish();
                break;
        }
    }


    @Override
    public void getCaptchaResult(String result) {
        tvVerify.setClickable(true);
        if (Boolean.valueOf(result)) {//获取验证码成功
            spUtils.put(Config.QUICK_VERIFY_TIME, System.currentTimeMillis());
            spUtils.put(Config.QUICK_PHONE, etPhone.getText().toString().trim());
            etPhone.setFocusable(true);
            etPhone.setFocusableInTouchMode(true);
            tvVerify.setClickable(true);
            ARouter.getInstance().build(AroutePath.LOGIN_CODE_LOGIN)
                    .withString("phone", phoneNum)
                    .navigation();


        } else {
            showToast("获取验证码失败，请重试");
            tvVerify.setClickable(true);
            tvVerify.setBackgroundResource(R.drawable.login_able_click_bkg);
            tvVerify.setText("下一步");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        hideSoftInput(etPhone);
    }


    @Override
    public void showLogin(LoginSuccessData data) {

    }

    @Override
    public void showLoginFail(String msg, String failReason) {

    }

    @Override
    public void authLoginData(LoginSuccessData data) {
        baseHiddenCommitLoading();
        login_success_next(data, true);
    }

    LoginSuccessData data;

    private void login_success_next(LoginSuccessData data, boolean isAuthLogin) {
        if (!TextUtils.isEmpty(data.getCustomer_id())) {
            SPUtils.getInstance().put(Config.CUSTOMERID_TEMP, data.getCustomer_id());
        }
        if (!TextUtils.isEmpty(data.getToken())) {
            SPUtils.getInstance().put(Config.CUSTOMER_TOKEN_TEMP, data.getToken());
        }
        if (!TextUtils.isEmpty(data.getMobile())) {
            phone = data.getMobile();
        }
        UserDataManager.getInstance().updateUserStatus(data.isIs_disable());

        this.data = data;
        if (data.getInviter_code_select_pop() != null && data.getInviter_code_select_pop().bindInviterCode != null) {
            rewardId = data.getInviter_code_select_pop().bindInviterCode.rewardId;
        }
        if (data.isIs_disable()) {
            SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
            SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
            UtilActivity.finishStartNum(0, UtilActivity.getActivitySize());
            ARouter.getInstance().build(AroutePath.BAN_ACCOUNT_ACTIVITY)
                    .withString("content", data.getFreeze_reason()).navigation();
        } else if (data.isNeed_bind_phone()) {//需要绑定手机号
            Intent intent = new Intent(this, BindPhoneActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("auth_type", auth_type);
            bundle.putString("union_id", union_id);
            bundle.putString("nick_name", nick_name);
            bundle.putString("headimgurl", headimgurl);
            bundle.putSerializable("inviter_pop", data.getInviter_pop());
            bundle.putSerializable("login_success_data", data);
            intent.putExtras(bundle);
            getActivity().startActivityForResult(intent, BindPhoneActivity.REQUEST_CODE);
        } else if (data.isIs_show_code_select_pop() || data.isIs_show_user_info_pop()) {
            //TODO:fix
            //绑定邀请人弹窗
            Intent intent = new Intent(this, BindInviteActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("phone", "");
            bundle.putString("auth_type", auth_type);
            bundle.putString("union_id", union_id);
            bundle.putString("nick_name", nick_name);
            bundle.putString("headimgurl", headimgurl);
            bundle.putSerializable("inviter_pop", data.getInviter_pop());
            bundle.putSerializable("lg_data",data);
            intent.putExtras(bundle);
            getActivity().startActivityForResult(intent, BindInviteActivity.REQUEST_CODE);
        } else {
            //已绑定
            login_success_convert();
        }
    }

    private void login_success_convert() {
        if (data == null) {
            showToast("登录失败");
            return;
        }
        showToast("登录成功");
        SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
        SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
        UserDataManager.getInstance().updateUserStatus(data.isIs_disable());
        EventBusManager.post(EventBusManager.createLoginSuccessEvent());
        EventBusManager.post(EventBusManager.createHomeRefreshEvent());
        setResult();
        getActivity().finish();
        if (!UtilActivity.isCurActivity("MainActivity")) {
            startActivitryWithBundle(MainActivity.class, null);
        }
    }

    @Override
    public void authLoginError(String msg, String failReason) {
        if (failReason == null)
            baseHiddenCommitLoading();
        showToast(msg);
    }

    private void setResult() {
        if (getActivity().getIntent() != null && getActivity().getIntent().getExtras() != null) {
            Bundle bundle = getActivity().getIntent().getExtras();
            String result = bundle.getString("result_code");
            if (!TextUtils.isEmpty(result)) {
                getActivity().setResult(Integer.valueOf(result));
            }
        }
    }


    @Override
    public void showError(String msg) {
        if (tvVerify != null) {
            tvVerify.setClickable(true);
        }
        showToast(msg);
    }

    @Override
    public void checkSuccess() {

    }

    @Override
    public void checkError(String msg) {

    }

    @Override
    public void showInviteInfo(InviteInfoData inviteInfoData) {
        rewardId = "";
    }

    @Override
    public void showInviteInfoFail(String msg) {

    }

    @Override
    public void authBindSuccess(String code, AuthBindData data, String msg, String inviteCode) {
        UserDataManager.getInstance().updateInviteCode(inviteCode);
        if ("30000".equals(code)) {
            rewardId = data.getInviteInfo().getReward_id();
        } else {

            if (data != null) {
                if (!TextUtils.isEmpty(data.getCustomer_id())) {
                    SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
                } else {
                    SPUtils.getInstance().put(Config.CUSTOMERID, SPUtils.getInstance().getString(Config.CUSTOMERID_TEMP));
                }
                if (!TextUtils.isEmpty(data.getToken())) {
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
                } else {
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN_TEMP));
                }
            }
            EventBusManager.post(EventBusManager.createLoginSuccessEvent());
            EventBusManager.post(EventBusManager.createHomeRefreshEvent());
            setResult();
            getActivity().finish();
            if (!UtilActivity.isCurActivity("MainActivity")) {
                startActivitryWithBundle(MainActivity.class, null);
            }
        }
        baseHiddenCommitLoading();
        showToast(msg);
    }

    @Override
    public void authBindFailded(String msg) {
        baseHiddenCommitLoading();
        showToast(msg);
    }

    String nick_name, headimgurl;

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      微信回调事件
    //
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * 成功
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendSuccess(WXSendSuccessEvent successEvent) {
        Log.e("======quick", "wxSendSuccess: ");
        if (successEvent.getWxType() == WXSendTypeEnum.QUICK_LOGIN_EVENT_TYPE) {
            String code = successEvent.getCode();
            //获取用户信息
            getAccessToken(code);
        }
    }

    /**
     * 取消
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendCancel(WXSendCancelEvent cancelEvent) {
        Log.e("======quick", "wxSendCancel: ");

    }

    /**
     * 失败
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendFailed(WXSendFailedEvent failedEvent) {
        Log.e("======quick", "wxSendFailed: ");

    }


    private void getAccessToken(String code) {
        //获取授权
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=")
                .append(WeiXinManager.APP_ID)
                .append("&secret=")
                .append(WeiXinManager.SECRET)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        OkHttpUtils.ResultCallback<String> resultCallback = new OkHttpUtils.ResultCallback<String>() {
            @Override
            public void onSuccess(String response) {
                String access = null;
                String openId = null;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    access = jsonObject.getString("access_token");
                    openId = jsonObject.getString("openid");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //获取个人信息
                String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId;
                OkHttpUtils.ResultCallback<String> reCallback = new OkHttpUtils.ResultCallback<String>() {
                    @Override
                    public void onSuccess(String responses) {
                        try {
                            JSONObject jsonObject = new JSONObject(responses);
                            nick_name = jsonObject.getString("nickname");
                            headimgurl = jsonObject.getString("headimgurl");
                            union_id = jsonObject.getString("unionid");
                            if (getActivity() != null) {
                                ((getActivity())).runOnUiThread(() -> {
                                    baseShowCommitLoading("授权登录中");
                                });
                            }
                            mPresenter.authLogin(auth_type, headimgurl, nick_name, union_id, Config.uid, "");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
                    }
                };
                OkHttpUtils.get(getUserInfo, reCallback);
            }

            @Override
            public void onFailure(Exception e) {
                Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
            }
        };
        OkHttpUtils.get(loginUrl.toString(), resultCallback);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BindInviteActivity.REQUEST_CODE) {
            if (resultCode == BindInviteActivity.BIND_SUC_CODE) {
                setResult();
                getActivity().finish();
                if (!UtilActivity.isCurActivity("MainActivity")) {
                    startActivitryWithBundle(MainActivity.class, null);
                }
            }
        }
    }
}